package luogu.bfs;
//P2802 回家
//解决可能需要可多次访问问题
import java.util.*;

/**
 * @author :chenjie
 * @date :Created 2022/12/23 21:26
 */
public class GoHome {
    static class Pall{
        int x;
        int y;
        int hp;
        int l;

        public Pall(int x, int y, int hp, int l) {
            this.x = x;
            this.y = y;
            this.hp = hp;
            this.l = l;
        }

        @Override
        public String toString() {
            return "Pall{" +
                    "x=" + x +
                    ", y=" + y +
                    ", hp=" + hp +
                    ", l=" + l +
                    '}';
        }
    }
    static int n;
    static int m;
    static boolean[][]st=new boolean[10][10];
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        int[][]arr=new int[n][m];
        int x=0,y=0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j]=sc.nextInt();
                if(arr[i][j]==2){
                    x=i;
                    y=j;
                }
            }
        }
        int bfs = bfs(x, y, arr);
        System.out.println(bfs);

    }
    public static int bfs(int x,int y,int[][]arr){
        Queue<Pall> queue=new ArrayDeque<>();
        queue.add(new Pall(x,y,6,0));
        int[][]ph=new int[n][m];
        for (int i = 0; i < n; i++) {
            Arrays.fill(ph[i],-1);
        }
        ph[x][y]=6;
        int[]dx={0,0,1,-1};
        int[]dy={1,-1,0,0};
        while (!queue.isEmpty()){
            Pall axis = queue.remove();

            if(arr[axis.x][axis.y]==3){
                return axis.l;
            }
            if(axis.hp==1){
                continue;
            }
            for (int i = 0; i < 4; i++) {
                int a=axis.x+dx[i],b=dy[i]+axis.y;
                if(a>=0&&a<n&&b<m&&b>=0&&arr[a][b]!=0){
                    if(ph[a][b]==-1||(ph[a][b]!=-1&&axis.hp>ph[a][b])){//解决重复访问点的问题重复访问后本身应该会小于之前访问的点的hp值但是因为我加hp了所以我又大于之前访问的点的ph值了
                        if(arr[a][b]==4){
                            ph[a][b]=6;
                            queue.add(new Pall(a,b,6, axis.l+1));
                            continue;
                        }
                        queue.add(new Pall(a,b,axis.hp-1,axis.l+1));
                        ph[a][b]=axis.hp-1;
                    }

                }
            }
        }
        return -1;

    }

}